package com.ch04a;

import java.util.ArrayList;

public class CounterThreadSynchronized implements Runnable
{	
	String threadName;
	static boolean isBeingPrinted = false;
	private static boolean isLocked = false;
	ArrayList<CounterThreadSynchronized> threads = new ArrayList();
	
	public CounterThreadSynchronized(String name) {
		threadName = name;
		Thread t = new Thread(this);
		t.start();
	}
	public void run()
	{
		threads.add(this);
		printCounter();
	}
	
	public static void main(String args[]) {
		CounterThreadSynchronized t1 = new CounterThreadSynchronized("Thread 1");
		CounterThreadSynchronized t2 = new CounterThreadSynchronized("Thread 2");
		CounterThreadSynchronized t3 = new CounterThreadSynchronized("Thread 3");
	}
	
	private synchronized void printCounter() {
		while (isLocked) {
			try {
				System.out.println("Thread waiting is " + this.threadName);
				wait(300);
				System.out.println("Thread wait over for " + this.threadName);
			} catch (InterruptedException e) {
				System.out.println("Interrupted Exception for " + this.threadName);
				e.printStackTrace();
			}
		}
		synchronized(this) {
			isLocked = true;
			for (int i=0; i<1000000; i++)
			{
				if (i%100000 == 0)
					System.out.println(i + "," + this.threadName);
			}
			isLocked = false;
			for (CounterThreadSynchronized thread: threads) {
				if ((thread.threadName).equals(this.threadName)) {
					System.out.println("Notifying other threads " + this.threadName);
				} else {
					thread.notifyAll();
				}
			}
			
		}
	}
}

